﻿Imports BUS
Imports DTO
Imports Microsoft.Office.Tools.Excel
Imports System.Drawing.Printing

Public Class frmTraCuuBoKichDien
    Private bkdController As BoKichDienBUS
    Private _bkd As BoKichDienDTO
    Private indexGr As Integer = 0
    Private sListBoKichDien As New List(Of BoKichDienDTO)
    Public sListBoKichDienSelect As New List(Of Integer)
    Public dataBoKichDien As New DataTable

    '------------------------------------------------------'
    '                 Các hàm xử lý phụ                   '
    '------------------------------------------------------'
    Private Sub LockText(ByVal b As Boolean)
        txtDienApTu.ReadOnly = b
        txtDienApDen.ReadOnly = b
        txtCongSuatTu.ReadOnly = b
        txtCongSuatDen.ReadOnly = b
        txtGiaTu.ReadOnly = b
        txtGiaDen.ReadOnly = b
        If (b = True) Then
            txtDienApTu.ForeColor = Color.Black
            txtDienApDen.ForeColor = Color.Black
            txtCongSuatTu.ForeColor = Color.Black
            txtCongSuatDen.ForeColor = Color.Black
            txtGiaDen.ForeColor = Color.Black
            txtGiaTu.ForeColor = Color.Black
        End If
    End Sub

    Private Sub BlockButton(ByVal t As Control, ByVal h As Control, Optional ByVal capdo As Byte = 0)
        Select Case capdo
            Case 0
                t.Enabled = True
                h.Enabled = True
            Case 1
                t.Enabled = False
                h.Enabled = False
        End Select
    End Sub

    Private Sub ReSet()
        txtMaBKD.Text = ""
        txtTenBKD.Text = ""
        cbLoaiBKD.SelectedIndex = -1
        txtHangSX.Text = ""
        txtCongSuatTu.Text = ""
        txtCongSuatDen.Text = ""
        txtDienApTu.Text = ""
        txtDienApDen.Text = ""
        txtGiaTu.Text = ""
        txtGiaDen.Text = ""
    End Sub

    Private Function SelectNameLoai(ByVal idLoai As Integer)
        Dim sListName As List(Of LoaiBoKichDienDTO) = bkdController.SelectNameLoai(idLoai)
        Return sListName(0).TenLoai
    End Function

    Private Sub LoadGrid()
        bkdController = New BoKichDienBUS()
        dgvDuLieu.Rows.Clear()
        For i As Integer = 0 To sListBoKichDien.Count - 1
            dgvDuLieu.Rows.Add()
            dgvDuLieu.Rows.Item(i).Cells(0).Value = sListBoKichDien(i).MaBoKichDien
            dgvDuLieu.Rows.Item(i).Cells(1).Value = sListBoKichDien(i).TenBoKichDien
            dgvDuLieu.Rows.Item(i).Cells(2).Value = sListBoKichDien(i).HangSanXuat
            dgvDuLieu.Rows.Item(i).Cells(3).Value = SelectNameLoai(Val(sListBoKichDien(i).MaLoai))
            dgvDuLieu.Rows.Item(i).Cells(4).Value = sListBoKichDien(i).MaLoai
            dgvDuLieu.Rows.Item(i).Cells(5).Value = sListBoKichDien(i).DienApTai.ToString() + " Ah"
            dgvDuLieu.Rows.Item(i).Cells(6).Value = sListBoKichDien(i).CongSuatTai.ToString() + " W"
            dgvDuLieu.Rows.Item(i).Cells(7).Value = sListBoKichDien(i).Gia
        Next
    End Sub



    Public Sub AddList(ByVal sListSelect As IList(Of Integer))
        For i As Integer = 0 To sListSelect.Count - 1
            bkdController = New BoKichDienBUS()
            Dim j As Integer = Val(sListSelect.Item(i))
            sListBoKichDien.AddRange(bkdController.SelectById(j))
        Next
    End Sub

    '------------------------------------------------------'
    '                 Các Hàm Xử Lý Chính               '
    '------------------------------------------------------'








    Private Sub btnTatCa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTatCa.Click

        bkdController = New BoKichDienBUS()
        sListBoKichDien = bkdController.GetData()
        LoadGrid()

    End Sub

    Private Sub btnTim_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTim.Click

        Dim MAcQuy As Integer = Val(txtMaBKD.Text)
        Dim TAcQuy As String = txtTenBKD.Text
        Dim MLoai As Integer = cbLoaiBKD.SelectedValue
        Dim HSX As String = txtHangSX.Text
        Dim DienApMin As Single = Val(txtDienApTu.Text)
        Dim DienApMax As Single = Val(txtDienApDen.Text)
        Dim CongSuatMin As Single = Val(txtCongSuatTu.Text)
        Dim CongSuatMax As Single = Val(txtCongSuatDen.Text)
        Dim GiaMin As Integer = Val(txtGiaTu.Text)
        Dim GiaMax As Integer = Val(txtGiaDen.Text)
        _bkd = New BoKichDienDTO(MAcQuy, TAcQuy, MLoai, HSX, DienApMin, DienApMax, CongSuatMin, CongSuatMax, GiaMin, GiaMax)
        bkdController = New BoKichDienBUS()
        sListBoKichDien = bkdController.TimKiem(_bkd)
        If sListBoKichDien.Count() <= 0 Then
            MsgBox("Không tìm thấy kết quả!")
            sListBoKichDien.Clear()
        End If
        LoadGrid()
    End Sub

    Private Sub btnNhapLai_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNhapLai.Click
        ReSet()
    End Sub

    Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
        Me.Close()
    End Sub


    Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click
        For Each i As DataGridViewRow In dgvDuLieu.SelectedRows
            Dim j As Integer = Integer.Parse(i.Cells(0).Value.ToString())
            sListBoKichDienSelect.Add(j)
        Next
        If sListBoKichDienSelect.Count > 0 Then
            frmLuuBoKichDien.AddList(sListBoKichDienSelect)
            frmLuuBoKichDien.MdiParent = Me.MdiParent
            frmLuuBoKichDien.Show()

            LoadGrid()
            sListBoKichDienSelect.Clear()
        Else
            MsgBox("Bạn chưa chọn!", vbExclamation, "Thông báo")
        End If
    End Sub

    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
        Dim qs = MsgBox("Bạn chắc chắn muốn xóa tất cả thông tin ", vbInformation + vbYesNo, "Thông báo")
        For Each i As DataGridViewRow In dgvDuLieu.SelectedRows
            Dim j As Integer = Integer.Parse(i.Cells(0).Value.ToString())
            sListBoKichDienSelect.Add(j)
        Next
        If qs = vbYes Then
            If sListBoKichDienSelect.Count > 0 Then
                For j As Integer = 0 To sListBoKichDienSelect.Count - 1
                    bkdController.DeleteProduct(sListBoKichDienSelect.Item(j))
                Next
                MsgBox("Dữ liệu đã xóa thành công", vbInformation, "Thông báo")
                bkdController = New BoKichDienBUS()
                sListBoKichDien = bkdController.GetData()
                LoadGrid()
            End If
        Else
            MsgBox("Đã hủy thao tác xóa!", vbExclamation, "Thông báo")
        End If
    End Sub

    Public Sub Export_To_Exel(ByVal _DataSet As DataTable, ByVal _List_Col As String, ByVal Path As String)
        '- _Dataset: lưu dữu liệu cần Export
        '- _List_Col: Danh sách tên cột hiển thị. Tên cột cách nhau dấu ','
        '- Path: Đường dẫn lưu file excel
        Dim col, row As Integer
        Dim arrListcol() As String
        arrListcol = _List_Col.Split(",")

        If _DataSet.Rows.Count <= 0 Then
            Exit Sub
        End If

        Dim Excel As Object = CreateObject("Excel.Application")
        If Excel Is Nothing Then
            MessageBox.Show("Để xuất ra Excel, máy bạn phải cài đặt bộ phần mềm Microsoft Office.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Return
        End If

        'Export to Excel process
        Try
            With Excel
                .SheetsInNewWorkbook = 1
                .Workbooks.Add()
                .Worksheets(1).Select()

                Dim i As Integer = 2
                .cells(1, 3).value = "Date:" + Format(Now, "MMM-dd-yyyy")
                .cells(2, i).value = "No"
                .cells(2, i).EntireRow.Font.Bold = True
                For col = 0 To arrListcol.Length - 1
                    i += 1
                    .cells(2, i).value = arrListcol(col).ToUpper()
                    .cells(2, i).EntireRow.Font.Name = "Times New Roman"
                    .cells(2, i).EntireRow.Font.Size = 10
                    .cells(2, i).EntireRow.Font.Bold = True
                Next
                i = 3
                Dim k As Integer = 3

                For col = 0 To _DataSet.Columns.Count - 1
                    i = 3
                    For row = 0 To _DataSet.Rows.Count - 1
                        .Cells(i, 2).Value = i - 2
                        .Cells(i, k).Value = _DataSet.Rows(row).ItemArray(col)
                        i += 1
                    Next
                    k += 1
                Next
                .Columns.AutoFit()
                .ActiveCell.Worksheet.SaveAs(Path)
            End With
            System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
            Excel = Nothing
            MessageBox.Show("Xuất dữ liệu thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)

            Dim proc As System.Diagnostics.Process
            For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
                proc.Kill()
            Next

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        dataBoKichDien = New DataTable()
        dataBoKichDien.Columns.Add("MaBoKichDien", GetType(String))
        dataBoKichDien.Columns.Add("TenBoKichDien", GetType(String))
        dataBoKichDien.Columns.Add("HangSanXuat", GetType(String))
        dataBoKichDien.Columns.Add("TenLoai", GetType(String))
        dataBoKichDien.Columns.Add("DienApTai", GetType(String))
        dataBoKichDien.Columns.Add("CongSuatTai", GetType(String))
        dataBoKichDien.Columns.Add("Gia", GetType(String))
        For i As Integer = 0 To Me.dgvDuLieu.RowCount - 1
            Dim dr As DataRow = dataBoKichDien.NewRow
            Dim hoangvu As String = dgvDuLieu.Rows.Item(i).Cells(2).Value.ToString
            dr("MaBoKichDien") = dgvDuLieu.Rows.Item(i).Cells(0).Value.ToString
            dr("TenBoKichDien") = dgvDuLieu.Rows.Item(i).Cells(1).Value.ToString
            dr("TenLoai") = dgvDuLieu.Rows.Item(i).Cells(3).Value.ToString
            dr("HangSanXuat") = dgvDuLieu.Rows.Item(i).Cells(2).Value.ToString
            dr("DienApTai") = dgvDuLieu.Rows.Item(i).Cells(5).Value.ToString
            dr("CongSuatTai") = dgvDuLieu.Rows.Item(i).Cells(6).Value.ToString
            dr("Gia") = dgvDuLieu.Rows.Item(i).Cells(7).Value.ToString
            dataBoKichDien.Rows.Add(dr)
        Next
        Try
            SaveFileExcel.Filter = "Excel (*.xls)|*.xls"
            SaveFileExcel.ShowDialog()
            Dim File_name = SaveFileExcel.FileName
            Export_To_Exel(dataBoKichDien, "Mã BKĐ,Tên BKĐ,Loại,Hãng Sản Xuất,Điện áp tải, Công suất tải,Giá", File_name)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop)
        End Try
    End Sub

    Private Sub cbChinhSua_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbChinhSua.CheckedChanged
        If cbChinhSua.Checked = True Then
            BlockButton(btnSua, btnXoa, 0)
        Else
            BlockButton(btnSua, btnXoa, 1)
        End If
    End Sub

    Private Sub cbNangCao_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbNangCao.CheckedChanged
        If cbNangCao.Checked = True Then
            LockText(False)
        Else
            LockText(True)
        End If
    End Sub

    Private Sub dgvDuLieu_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvDuLieu.CellContentClick

    End Sub

    Private Sub frmTraCuuBoKichDien_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        cbLoaiBKD.Items.Clear()
        Dim dt As New DataTable
        bkdController = New BoKichDienBUS()
        Dim sListlaq As New List(Of LoaiBoKichDienDTO)
        dt = bkdController.LoadComboListbox()
        If dt.Rows.Count > 0 Then
            cbLoaiBKD.DataSource = dt
            cbLoaiBKD.ValueMember = "MaLoai"
            cbLoaiBKD.DisplayMember = "TenLoai"
        End If
        cbLoaiBKD.SelectedIndex = -1
        LockText(True)
        BlockButton(btnSua, btnXoa, 1)
    End Sub

    Dim MyDataGridViewPrinter As DataGridViewPrinter
    Private Function SetupThePrinting() As Boolean
        If PrintDialog.ShowDialog() <> DialogResult.OK Then
            Return False
        End If

        PrintDocument.DocumentName = "Các Hệ Thống Điện Năng Lượng Mặt Trời Phù Hợp"
        PrintDocument.PrinterSettings = PrintDialog.PrinterSettings
        PrintDocument.DefaultPageSettings = PrintDialog.PrinterSettings.DefaultPageSettings
        PrintDocument.DefaultPageSettings.Margins = New Margins(40, 40, 40, 40)

        If MessageBox.Show("Canh chính giữa trang?", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            MyDataGridViewPrinter = New DataGridViewPrinter(dgvDuLieu, PrintDocument, True, True, "Các Hệ Thống Điện Năng Lượng Mặt Trời Phù Hợp", New Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, True)
        Else
            MyDataGridViewPrinter = New DataGridViewPrinter(dgvDuLieu, PrintDocument, False, True, "Customers", New Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, True)
        End If
        Return True
    End Function

    Private Sub btnIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIn.Click
        'PrintPreviewDialog1.Document = PrintDocument1
        'PrintDocument1.DefaultPageSettings.Landscape = True
        'PrintPreviewDialog1.ShowDialog()
        If SetupThePrinting() Then
            PrintDocument.Print()
        End If

    End Sub

    Private Sub btnXemTruoc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXemTruoc.Click
        If SetupThePrinting() Then
            PrintPreviewDialog.Document = PrintDocument
            PrintPreviewDialog.ShowDialog()
        End If
    End Sub

    Private Sub PrintDocument_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument.PrintPage
        Dim more As Boolean = MyDataGridViewPrinter.DrawDataGridView(e.Graphics)
        If more = True Then
            e.HasMorePages = True
        End If
    End Sub

End Class